/* Includes ------------------------------------------------------------------*/
#include "bsp_key.h"
/* Private includes ----------------------------------------------------------*/
#include "stdio.h"
#include "main.h"
#include "flexible_button.h"
/* Private define ------------------------------------------------------------*/
#define BSP_KEY_PRESSED_LEVEL GPIO_PIN_SET
/* Private macro -------------------------------------------------------------*/
#define ENUM_TO_STR(e) (#e)
/* Private typedef -----------------------------------------------------------*/
typedef enum
{
  BSP_KEY_ID_WKUP = 0,
  BSP_KEY_ID_USER,
  BSP_KEY_ID_MAX
}BSP_KEY_ID_T;

/* Private variables ---------------------------------------------------------*/
static char *enum_event_string[] = {
    ENUM_TO_STR(FLEX_BTN_PRESS_DOWN),
    ENUM_TO_STR(FLEX_BTN_PRESS_CLICK),
    ENUM_TO_STR(FLEX_BTN_PRESS_DOUBLE_CLICK),
    ENUM_TO_STR(FLEX_BTN_PRESS_REPEAT_CLICK),
    ENUM_TO_STR(FLEX_BTN_PRESS_SHORT_START),
    ENUM_TO_STR(FLEX_BTN_PRESS_SHORT_UP),
    ENUM_TO_STR(FLEX_BTN_PRESS_LONG_START),
    ENUM_TO_STR(FLEX_BTN_PRESS_LONG_UP),
    ENUM_TO_STR(FLEX_BTN_PRESS_LONG_HOLD),
    ENUM_TO_STR(FLEX_BTN_PRESS_LONG_HOLD_UP),
    ENUM_TO_STR(FLEX_BTN_PRESS_MAX),
    ENUM_TO_STR(FLEX_BTN_PRESS_NONE),
};

static char *enum_btn_id_string[] = {
    ENUM_TO_STR(BSP_KEY_WKUP),
    ENUM_TO_STR(BSP_KEY_USER),
    ENUM_TO_STR(BSP_KEY_ID_MAX),
};

static flex_button_t key_list[BSP_KEY_ID_MAX] = {0};
/* Private function prototypes -----------------------------------------------*/
/* Private user code ---------------------------------------------------------*/

static uint8_t BSP_KEY_Read(void *p_arg)
{
  uint8_t value_ret = 0;
  flex_button_t *p_button = (flex_button_t *)p_arg;
  switch (p_button->id)
  {
  case BSP_KEY_ID_WKUP:
    value_ret = HAL_GPIO_ReadPin(KEY_WKUP_GPIO_Port, KEY_WKUP_Pin);
    break;
  case BSP_KEY_ID_USER:
    value_ret = HAL_GPIO_ReadPin(KEY_0_GPIO_Port, KEY_0_Pin);
    break;
  default:
    break;
  }
  return value_ret;
}

static void BSP_KEY_Callback(void *p_arg)
{
  flex_button_t *p_button = (flex_button_t *)p_arg;

  printf("id: [%d - %s]  event: [%d - %30s]  repeat: %d\r\n", 
        p_button->id, enum_btn_id_string[p_button->id],
        p_button->event, enum_event_string[p_button->event],
        p_button->click_cnt);

  switch (p_button->id)
  {
  case BSP_KEY_ID_WKUP:
    break;
  case BSP_KEY_ID_USER:
    break;
  default:
    break;
  }
}

void BSP_KEY_Init(void)
{
  for (uint8_t i = 0; i < BSP_KEY_ID_MAX; i++)
  {
    key_list[i].id = i;
    key_list[i].usr_button_read = BSP_KEY_Read;
    key_list[i].cb = BSP_KEY_Callback;
    key_list[i].pressed_logic_level = BSP_KEY_PRESSED_LEVEL;
    key_list[i].short_press_start_tick = FLEX_MS_TO_SCAN_CNT(1500);
    key_list[i].long_press_start_tick = FLEX_MS_TO_SCAN_CNT(3000);
    key_list[i].long_hold_start_tick = FLEX_MS_TO_SCAN_CNT(4500);
    flex_button_register(&key_list[i]);
  }
}
